package com.example.camera__demo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.os.Environment;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class SurfaceCamera extends Activity implements OnClickListener {
	SurfaceView surfaceView;
	Button button;
	Camera camera = null;
	File currentFile = null;
	
	SurfaceHolder.Callback surfaceHolder = new SurfaceHolder.Callback() {

		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {
			// TODO Auto-generated method stub
			stopPreview();
		}

		@Override
		public void surfaceCreated(SurfaceHolder holder) {
			// TODO Auto-generated method stub
			startPreview();
		}

		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
			// TODO Auto-generated method stub

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_surface);
		super.onCreate(savedInstanceState);
		initView();
	}

	protected void startPreview() {
		// TODO Auto-generated method stub
		camera = Camera.open();
		try {
			camera.setPreviewDisplay(surfaceView.getHolder());
			camera.setDisplayOrientation(90);
			camera.startPreview();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected void stopPreview() {
		// TODO Auto-generated method stub
		camera.stopPreview();
		camera.release();
		camera = null;
	}

	private void initView() {
		surfaceView = (SurfaceView) findViewById(R.id.sur_preview);
		button = (Button) findViewById(R.id.btn_photo);
		button.setOnClickListener(this);
		surfaceView.getHolder().addCallback(surfaceHolder);
	}

	@Override
	public void onClick(View v) {
		camera.takePicture(null, null, new Camera.PictureCallback() {
			@Override
			public void onPictureTaken(byte[] data, Camera camera) {
				// TODO Auto-generated method stub
				if(saveFile(data)!=null){
					Toast.makeText(getApplicationContext(), "success", 199).show();
				}
			}
		});
	}

	protected File saveFile(byte[] data) {
		File dir = new File(Environment.getExternalStorageDirectory(),"cameraphoto");
		if(!dir.exists()){
			dir.mkdirs();
		}
		currentFile = new File(dir,System.currentTimeMillis()+".jpg");
		if(!currentFile.exists()){
			try {
				currentFile.createNewFile();
				FileOutputStream fos = new FileOutputStream(currentFile);
				fos.write(data);
				fos.flush();
				fos.close();
				return currentFile;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}
}
